package polloBeta;

import Beans.Usuario;
import Daos.DaoBase;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;

/**
 *
 * @author angel
 */
public class Server implements Runnable {

    public ObjectOutputStream out;
    public ObjectInputStream in;
    private Socket clienteSocket;

    
    private Server(Socket s) {

        this.clienteSocket = s;
        
    }

    
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(9999);
            while( true ){
                System.out.println("esperando usuario");                
                new Thread( new Server(serverSocket.accept())).start();
                //ss.close();
            }

        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }

    }


    public void run() {
        try{
        out = new ObjectOutputStream(clienteSocket.getOutputStream());
        in = new ObjectInputStream(clienteSocket.getInputStream());
        System.out.println("Conexión Aceptada desde " + clienteSocket.getInetAddress()+
                clienteSocket.getInetAddress().getCanonicalHostName());

        while (true) {
            out.writeObject(recibeUsuarios((Usuario)in.readObject()));
            System.out.println();
//            Out.close();
//            In.close();
        }
        
        }catch( Exception ex ){
            System.out.println(ex.getMessage());
        }
    }




    public int recibeUsuarios(Usuario u){
            int retorno = 0;
        try {
            DaoBase db = new DaoBase();
            boolean conectar = db.conectar();
            boolean validar = db.validar(u);
            if(conectar){
                if(validar){
                    switch (u.getAcceso()){
                        case 1:
                            retorno = 1;
                            break;
                        case 2:
                            retorno = 2;
                            break;
                    }
                }else{
                    switch(u.getAcceso()){
                        case 1:
                            retorno = 2;
                            break;
                        case 2:
                            retorno = 1;
                            break;
                    }
                } 
            }
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
            retorno = 0;
        } return retorno;
    }

}

